package com.example.springboot_zhenhong.service;

import com.example.springboot_zhenhong.pojo.User;
import com.example.springboot_zhenhong.pojo.dto.UserDto;
import com.example.springboot_zhenhong.repository.IUserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service //把UserService标记成spring的bean
public class UserService implements IUserService{
    @Autowired
    IUserRepository userRepository;
    @Override
    public User add(UserDto user) {
        User user1 = new User();
        BeanUtils.copyProperties(user,user1);
        return userRepository.save(user1);
    }

    @Override
    public User getUser(Integer userId) {
        //orElseThrow：如果查不到就会抛出以下异常
        return userRepository.findById(userId).orElseThrow(()->{
           throw new IllegalArgumentException("用户不存在，参数异常！");
        });
    }

    @Override
    public User edit(UserDto user) {
        User user1 = new User();
        BeanUtils.copyProperties(user,user1);
        return userRepository.save(user1);
    }
}
